const { UserModel } = require("../model/module/xsp_db");
const jwtUtils = require("../utils/jwt");
const jwt = require("jsonwebtoken");
exports.login = async (req, res) => {
  // 验证用户名和密码
  const user = await UserModel.findOne({ username: req.body.username });
  if (!user || !user.password === req.body.password) {
    return res.status(401).json({ error: "账号或密码错误" });
  }
  // 生成并返回JWT和Refresh Token
  const accessToken = jwtUtils.generateAccessToken(user);
  const refreshToken = jwtUtils.generateRefreshToken(user._id);
  res.json({ accessToken, refreshToken });
};

// 实现刷新JWT的接口，验证Refresh Token并生成新的JWT
exports.refreshToken = async (req, res) => {
  try {
    const decoded = jwt.verify(
      req.body.refreshToken,
      'secret'
    );
    const user = await UserModel.findById(decoded.userId);
    if (!user) {
      return res.status(401).json({ error: "没有找到该用户信息" });
    }
    const newAccessToken = jwt.sign({ _id: user._id, username: user.username },'secret', { expiresIn: '5s' });
    res.send({code:200, accessToken: newAccessToken})
  } catch (error) {
    res.send({code:401,msg:'长token过期，请重新登陆'})
  }
};
